package pers.kw.config.oauth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 通过添加自定义过滤器，实现对oauth标准接口增加自定义参数
 */
@Component
public class OauthAuthenticationFilter extends GenericFilterBean implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(OauthAuthenticationFilter.class);

    private ApplicationContext applicationContext;

    private RequestMatcher requestMatcher;

    private static final String URL = "/oauth/token";

    public OauthAuthenticationFilter() {
        this.requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(URL, "GET"),
                new AntPathRequestMatcher(URL, "POST")
        );
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (requestMatcher.matches(request)) {
            //将自定义参数，保存到当前本地线程中
            MyParamValue paramValue = new MyParamValue();
            paramValue.setAuthParameters(request.getParameterMap());
            MyParamValueThreadLocal.set(paramValue);
            filterChain.doFilter(request, response);
            //执行完成，清除线程本地变量
            MyParamValueThreadLocal.remove();
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
